#!/usr/bin/perl
# 2014/06/02 count properties type of each associations

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [association file] -p [properties file]\n";
}
my %opt;
getopts("i:p:", \%opt);
my $FILE_aso = $opt{i};
my $FILE_property = $opt{p};

my $TOTAL_PEAKS = 0;
my %PROPERTIES;
my %DEF;
my $fh_pro = IO::File->new($FILE_property) or die "cannot open $FILE_property: $!";
while($_ = $fh_pro->getline()){
	s/\r?\n//;
	my ($name, @properties) = split /\t/;
	if(@properties > 0){
		$DEF{$name} = \@properties;
	}
	foreach my $key(@properties){
		$PROPERTIES{$key}++;
	}
	$TOTAL_PEAKS++;
}
$fh_pro->close();


my @pros;
foreach my $key(keys %PROPERTIES){
	push @pros, $key;
}

my %ASO_COUNT;
my $TOTAL_association = 0;
my $fh_aso = IO::File->new($FILE_aso) or die "cannot open $FILE_aso: $!";
while($_ = $fh_aso->getline()){
	s/\r?\n//;
	my ($name1, $loc1, $name2, $loc2, $interaction, $pval) = split /\t/;
	if($interaction <= 2){
		next;
	}

	$TOTAL_association++;
	foreach my $key1(@{$DEF{$name1}}){
		foreach my $key2(@{$DEF{$name2}}){
			$ASO_COUNT{$key1}{$key2}++;
		}
	}
}
$fh_aso->close();


print "\t" . join("\t", @pros) . "\tTOTAL\n";
for(my $i = 0; $i < @pros; $i++){
	my $key1 = $pros[$i];
	print "$key1";
	for(my $j = 0; $j < @pros; $j++){
		my $key2 = $pros[$j];
		my $SUM = 0;
		if(exists $ASO_COUNT{$key1}{$key2}){
			$SUM += $ASO_COUNT{$key1}{$key2};
		}
		if(exists $ASO_COUNT{$key2}{$key1}){
			$SUM += $ASO_COUNT{$key2}{$key1};
		}
		if($key1 eq $key2){
			$SUM /= 2;
		}
		print "\t$SUM";
	}
	print "\t$PROPERTIES{$key1}\n";
}

print "TOTAL";
foreach my $key(@pros){
	print "\t$PROPERTIES{$key}";
}
print "\t$TOTAL_association\n";

warn ("total peaks: $TOTAL_PEAKS\n");














